package com.unitd.frame.comm.utils;

import com.unitd.frame.comm.utils.encrypt.DES;
import com.unitd.frame.comm.utils.encrypt.MD5Utils;
import com.unitd.frame.comm.utils.encrypt.base64.Base64Util;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @desc 简单加解密工具类
 * @filename SimpleCryptUtils.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016/11/13
 */
public class SimpleCryptUtils {

	private static final String KEY_TAIL = "j@";

	/**
	 * @desc 加密方法
	 * @param key 需要加密的key
	 * @param data 需要加密的数据
	 * @return
	 */
	public static String encrypt(String key, String data) {
		key = MD5Utils.encryptShort(key) + KEY_TAIL;
		String encode = DES.encrypt(key, data);
		byte[] bytes = Base64Util.encodeToByte(encode.getBytes(StandardCharsets.UTF_8));
		return new String(bytes, StandardCharsets.UTF_8);
	}

	/**
	 * @desc 解密方法
	 * @param key 需要解密的key
	 * @param data 需要解密的数据
	 * @return
	 */
	public static String decrypt(String key, String data) {
		key = MD5Utils.encryptShort(key) + KEY_TAIL;
		byte[] bytes = Base64Util.decode(data);
		data = new String(bytes, StandardCharsets.UTF_8);
		return DES.decrypt(key, data);
	}


	public static void main(String[] args) {
		long s = System.currentTimeMillis();
		for (int i = 0; i < 2; i++) {
			String key = UUID.randomUUID().toString().replaceAll("-", "");
			String data = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
			String encode = encrypt(key, data);
			if (!data.equals(decrypt(key, encode))) {
				System.out.println(encode);
			}

		}

		System.out.println(System.currentTimeMillis() - s);
	}
}